import React, { useState } from 'react';
import {
  Button,
  Form,
  Input,
  message,
  Popconfirm,
  Space,
  DatePicker,
  Tag,
} from 'antd';
import {
  PlusOutlined,
  EditOutlined,
  DeleteOutlined,
  SearchOutlined,
  DragOutlined
} from '@ant-design/icons';
import {
  deleteApi,
} from './services';
import dayjs from 'dayjs';
import { DragEndEvent } from '@dnd-kit/core';
import { arrayMove, } from '@dnd-kit/sortable';
import { useTableRequest } from '@/hooks/useTableRequest';
import PageContent from '@/layout/pageContent';
import DragTable from '@/components/DragTable';
import EditForm from './components/EditForm';
import { useNavigate } from 'react-router-dom';

const { RangePicker } = DatePicker;

export interface Banner {
  id?: number;
  name: string;
  comment: string;
  status: number;
  createdAt?: string;
  updatedAt?: string;
}



const BannerList: React.FC = () => {
  const navigate = useNavigate();
  const [searchForm] = Form.useForm();
  const [handleModalInfo, setHandleModalInfo] = useState<{ visible: boolean, id?: number }>({
    visible: false
  });

  const {
    tableProps,
    refresh,
    setSearchParams,
    resetPagination,
  } = useTableRequest<Banner>({
    url: "/tableInfo/selectList",
    orderBy:"id asc"
    // immediate:false
  });

  const handleSearch = (values: any) => {
    const params = {
      ...values,
      ...(values.date ? {
        fromDate: values.date[0],
        toDate: values.date[1]
      } : {})
    };
    delete params.date;
    setSearchParams(params);
    resetPagination();
  };

  const handleResetSearch = () => {
    searchForm.resetFields();
    setSearchParams({});
    resetPagination();
  };

  const handleDelete = async (id: number) => {
    try {
      const res = await deleteApi(id);
      if (res.code === 200) {
        message.success('删除成功');
        refresh();
      }
    } catch (error) {
      message.error('删除失败');
    }
  };



  const columns = [
    {
      title: 'id',
      dataIndex: 'id',
      width: 60,
      sorter: true,

    },
    {
      title: '名称',
      dataIndex: 'name',
      width: 120,
      sorter: true,
      render: (_: any, record: Banner) => {
        return (
          <Button
          type="link"
          size="small"
          onClick={() => {
            navigate(`/tableInfo/detail/${record.id}`)
          }}
        >{record.name}</Button>

        )
      },

    },

    {
      title: '描述',
      dataIndex: 'comment',
      width: 100,
    },
    {
      title: '模版类型',
      dataIndex: 'templateType',
      width: 100,
    },
    {
      title: '子表',
      dataIndex: 'subTable',
      width: 100,
    },
    
    {
      title: '状态',
      dataIndex: 'status',
      width: 70,
      render: (status: number) => (
        <Tag color={status === 1 ? 'success' : 'error'}>
          {status === 1 ? '启用' : '禁用'}
        </Tag>
      ),
    },
    {
      title: '创建时间',
      dataIndex: 'createdAt',
      width: 150,
      render: (text: string) => dayjs(text).format('YYYY-MM-DD HH:mm'),
    },
    {
      title: '操作',
      key: 'action',
      width: 100,
      render: (_: any, record: Banner) => (
        <Space size="middle">
          <Button
            type="link"
            icon={<EditOutlined />}
            size="small"
            onClick={() => {
              setHandleModalInfo({
                visible: true,
                id: record.id
              })
            }}
          />
          <Popconfirm
            title="确定要删除这个Banner吗？"
            onConfirm={() => handleDelete(record.id!)}
          >
            <Button
              type="link"
              danger
              size="small"

              icon={<DeleteOutlined />}
            />
          </Popconfirm>
        </Space>
      ),
    },
  ];
  return (
    <PageContent
      title="Banner设置"
      extra={

        <Button
          type="primary"
          icon={<PlusOutlined />}
          onClick={() => {
            navigate(`/tableInfo/add`)
          }}
        >
          新建Banner
        </Button>
      }
    >
      {/* 搜索表单 */}
      <Form
        form={searchForm}
        layout="inline"
        onFinish={handleSearch}
        style={{ marginBottom: 16 }}
      >
        <Form.Item name="title" label="名称">
          <Input placeholder="请输入Banner名称" />
        </Form.Item>
        <Form.Item name="date" label="日期范围">
          <RangePicker />
        </Form.Item>
        <Form.Item>
          <Space>
            <Button
              type="primary"
              htmlType="submit"
              icon={<SearchOutlined />}
            >
              搜索
            </Button>
            <Button onClick={handleResetSearch}>
              重置
            </Button>
          </Space>
        </Form.Item>
      </Form>
      <DragTable
        // rowKey="id"
        draggable={false}
        columns={columns}
        {...tableProps}
        scroll={{ x: 1000 }}
      />

      <EditForm
        id={handleModalInfo.id}
        onCancel={() => { setHandleModalInfo({ visible: false }) }}
        modalVisible={handleModalInfo.visible}
        onSuccess={() => { refresh() }}
      />
    </PageContent>
  );
};

export default BannerList;